package com.ccf.business.etl.flow;

import com.alibaba.fastjson.JSON;
import com.component.api.constants.ComponentConstants;
import com.component.api.model.dto.MapColumnDTO;
import com.component.api.model.dto.ToAcolumnDTO;
import com.common.utils.tool.StringUtil;
import com.ccf.business.etl.model.RuleGroup;
import com.ccf.business.etl.model.vo.ToAcolumnVO;
import com.common.model.exception.ParamFomatException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 *
 * @author xianggj
 * @Date 2021/11/30 14:45
 **/
public class DataToAParamHandler extends ParamHandler {

    @Override
    protected Map<String, String> finishingParam() {
        Map<String, String> params = getParams();
        String columns = params.get(ComponentConstants.IN_COLUMNS);
        if (StringUtil.isJsonBlank(columns)){
            throw new ParamFomatException("缺少配置参数columns");
        }
        try {
            List<ToAcolumnDTO> toAcolumnDTOs = new ArrayList<>();
            List<ToAcolumnVO> toAcolumnVOs = JSON.parseArray(columns, ToAcolumnVO.class);
            for (ToAcolumnVO t : toAcolumnVOs) {
                ToAcolumnDTO toAcolumnDTO = new ToAcolumnDTO();
                toAcolumnDTO.setField(t.getField());
                RuleGroup byId = iRuleGroupService.getById(t.getRule());
                if (byId != null){
                    String groupJson = byId.getGroupJson();
                    List<ToAcolumnDTO.Rule> rules =
                            JSON.parseArray(groupJson, ToAcolumnDTO.Rule.class);
                    toAcolumnDTO.setRules(rules);
                }
                if (t.getMainVal() != null){
                    toAcolumnDTO.addRules(new ToAcolumnDTO.Rule(t.getMainVal(), t.getStartVal(), t.getEndVal()));
                }
                toAcolumnDTOs.add(toAcolumnDTO);
            }

            params.put(ComponentConstants.COLUMNS, JSON.toJSONString(toAcolumnDTOs));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParamFomatException("参数格式错误");
        }
        return params;
    }
}
